package lab3;

/**
 * Mex10 - shows how we can set up a group of threads
 * 
 * @author Anthony Varghese
 */
public class Mex10 {
	private static MexList in;
	private static final int NUMBER_OF_THREADS = 100;
	private static final int NUMBER_OF_ITERATIONS = 20;

	/**
	 * SimpleThread - our simple thread class
	 */
	private static class SimpleThread extends Thread{
		public SimpleThread( ThreadGroup g, String id){
			super( g, id );
		}
		public void run(){
			for (int i=0; i<NUMBER_OF_ITERATIONS; i++)
				in.add( "Group: " + getThreadGroup() + " id: " + getName() + " iter: " + i );

			try {	sleep(1000); } catch (InterruptedException e) {
				System.out.println("   ... thread " + getThreadGroup() + ":" + getName() + " done!");
			}
		}
	}
	/**
	 * MexList class - uses a Java util container internally
	 */
	private static class MexList{
		private java.util.List<String> store;
		public MexList(){
			store = new java.util.ArrayList<String>();
		}
		public void add(String x){
			store.add( x );
		}
		public int size(){ return store.size(); }
	}
	
	/**
	 * main - main method for Mex8
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		System.out.println("Mex10 program starting ...");

		in = new MexList();
		
		// We will set up a main group:
		ThreadGroup group1 = new ThreadGroup( "Group" );
		for (int i=0; i<NUMBER_OF_THREADS; i++)
			(new SimpleThread( group1, "t"+i )).start();
		System.out.println(
				"   a total of " + NUMBER_OF_THREADS + " threads were created \n" +
				"   with each thread creating " + NUMBER_OF_ITERATIONS + " Strings,\n" +
				"    the total number of Strings in the array should be: " + (NUMBER_OF_THREADS * NUMBER_OF_ITERATIONS) +"\n");

		// create an array of threads in group - so that we can
		//   join them all later
		int c = group1.activeCount();
		Thread g1[] = new Thread[ c ];
		group1.enumerate(g1);

		System.out.println(	"   a total of " + NUMBER_OF_THREADS + " threads are active \n");

		// wait for all threads to be done:
		for (Thread t : g1)
			t.join();

		System.out.println(" Actual number of Strings in the array is " + in.size() );
		System.out.println("... program done!");
	}
}